package com.ufo.store.management.ui.activity;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.net.DownloadServer;
import com.ufo.store.management.utils.ScreenUtil;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.ToastUtils;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.error.ServerError;
import com.yanzhenjie.nohttp.error.StorageReadWriteError;
import com.yanzhenjie.nohttp.error.StorageSpaceNotEnoughError;
import com.yanzhenjie.nohttp.error.TimeoutError;
import com.yanzhenjie.nohttp.error.URLError;
import com.yanzhenjie.nohttp.error.UnKnownHostError;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 *  作者：taoli on 2017/9/11 0011 09:18
 *  
 */
public class PictureViewActivity extends BaseActivity {
    private ArrayList<String> imgUrlList, imgDescriptionList = null;
    private int mDefaultPosition = 0;

    private ImageView mReturnIv = null;
    private ViewPager mPictureVp = null;
    private PicturePagerAdapter mPictureAdapter = null;
    private RelativeLayout mTitleRl = null;
    private RelativeLayout mBottomRl = null;
    private TextView mContentTv = null;
    private TextView mContentPosTv = null;
    private TextView mContentTotalTv = null;
    private ImageView mDownloadIv = null;
    private ScrollView mContentSv = null;

    private boolean isControllerHiden = false;
    private boolean mIsReturning = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarColor(this, R.color.transparent, false);
        initData();
        initView();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finishAfterTransition();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void finishAfterTransition() {
        mIsReturning = true;
        super.finishAfterTransition();
    }

    private void scheduleStartPostponedTransition(final View sharedElement) {
        sharedElement.getViewTreeObserver().addOnPreDrawListener(
                new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        sharedElement.getViewTreeObserver().removeOnPreDrawListener(this);
                        startPostponedEnterTransition();
                        return true;
                    }
                });
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            ArrayList list = intent.getExtras().getParcelableArrayList("list");
            imgUrlList = (ArrayList<String>) list.get(0);
            imgDescriptionList = (ArrayList<String>) list.get(1);
            mDefaultPosition = getIntent().getExtras().getInt("pos");
        }
    }

    private void initView() {
        setContentView(R.layout.activity_pictureview);
        postponeEnterTransition();
        mTitleRl = (RelativeLayout) findViewById(R.id.layout_title);
        mBottomRl = (RelativeLayout) findViewById(R.id.layout_bottom);
        mPictureVp = (ViewPager) findViewById(R.id.gallery);
        mContentTv = (TextView) findViewById(R.id.tv_picture_content);
        mContentPosTv = (TextView) findViewById(R.id.tv_picture_position);
        mContentTotalTv = (TextView) findViewById(R.id.tv_picture_total);
        mDownloadIv = (ImageView) findViewById(R.id.download_iv);
        mContentSv = (ScrollView) findViewById(R.id.sc_picture_content);
        mReturnIv = (ImageView) findViewById(R.id.iv_back);
        mReturnIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAfterTransition();
            }
        });
        mDownloadIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createFileFolder();
                DownloadServer.getInstance().download(PictureViewActivity.this, imgUrlList.get(mPictureVp.getCurrentItem()), BarApplication.mSavePictureDirPath, new DownloadListener() {
                    @Override
                    public void onDownloadError(int what, Exception exception) {
                        Logger.e(exception);
                        int message;
                        if (exception instanceof ServerError) {
                            message = R.string.download_error_server;
                        } else if (exception instanceof NetworkError) {
                            message = R.string.download_error_network;
                        } else if (exception instanceof StorageReadWriteError) {
                            message = R.string.download_error_storage;
                        } else if (exception instanceof StorageSpaceNotEnoughError) {
                            message = R.string.download_error_space;
                        } else if (exception instanceof TimeoutError) {
                            message = R.string.download_error_timeout;
                        } else if (exception instanceof UnKnownHostError) {
                            message = R.string.download_error_un_know_host;
                        } else if (exception instanceof URLError) {
                            message = R.string.download_error_url;
                        } else {
                            message = R.string.download_error_un;
                        }
                        ToastUtils.show(message);
                    }

                    @Override
                    public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {
                        ToastUtils.show("开始下载");
                    }

                    @Override
                    public void onProgress(int what, int progress, long fileCount, long speed) {

                    }

                    @Override
                    public void onFinish(int what, String filePath) {
                        ToastUtils.show(R.string.download_status_finish);
                    }

                    @Override
                    public void onCancel(int what) {

                    }
                });
            }
        });

        mPictureAdapter = new PicturePagerAdapter();
        mPictureVp.setAdapter(mPictureAdapter);
        mPictureVp.setOnPageChangeListener(new PisturePageChangeListener());
        mPictureVp.setCurrentItem(mDefaultPosition);
        mPictureAdapter.setOnClickListener(new OnClickListener() {
            @Override
            public void onPictureClick(PagerAdapter adapter, View view, int position) {
                if (isControllerHiden) {
                    // 显示
                    displayDescriptionWithAnimator(false);
                    displayTitleWithAnimator(false);
                    mPictureVp.invalidate();
                    isControllerHiden = false;
                } else {
                    // 隐藏
                    displayDescriptionWithAnimator(true);
                    displayTitleWithAnimator(true);
                    mPictureVp.invalidate();
                    isControllerHiden = true;
                }
            }
        });

        mContentPosTv.setText(String.valueOf(mDefaultPosition + 1));
        mContentTotalTv.setText(String.valueOf(imgUrlList.size()));

        if (null != imgDescriptionList && mDefaultPosition < imgDescriptionList.size()) {
            if (!"null".equals(imgDescriptionList.get(mDefaultPosition))) {
                mContentTv.setText(Html.fromHtml(imgDescriptionList.get(mDefaultPosition)));
            } else {
                mContentTv.setText("");
            }
        } else {
            mContentTv.setText("");
        }

        ObjectAnimator animatorTitle = ObjectAnimator.ofFloat(mTitleRl, View.TRANSLATION_Y, -getResources().getDimensionPixelSize(R.dimen.title_bar_top_margin), 0);
        ObjectAnimator animatorDescription = ObjectAnimator.ofFloat(mBottomRl, View.TRANSLATION_Y, ScreenUtil.getScreenSize(getActivity())[1], 0);
        List<Animator> titleAnimators = new ArrayList<>();
        titleAnimators.add(animatorTitle);
        titleAnimators.add(animatorDescription);
        AnimatorSet mOpenTitleAnimatorSet = new AnimatorSet();
        mOpenTitleAnimatorSet.playTogether(titleAnimators);
        mOpenTitleAnimatorSet.setDuration(700);
        mOpenTitleAnimatorSet.setInterpolator(new DecelerateInterpolator());
        mOpenTitleAnimatorSet.start();

        scheduleStartPostponedTransition(mPictureVp);
    }

    /**
     * 创建apk下载目录
     */
    private static void createFileFolder() {
        File downloadDir = new File(BarApplication.mSaveDirPath);
        if (!downloadDir.exists()) downloadDir.mkdir();
        File downloadApkDir = new File(BarApplication.mSavePictureDirPath);
        if (!downloadApkDir.exists()) downloadApkDir.mkdir();
    }

    public class PicturePagerAdapter extends PagerAdapter {
        private OnClickListener mListener = null;

        public PicturePagerAdapter() {
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View itemView = LayoutInflater.from(PictureViewActivity.this).inflate(R.layout.item_pager_gallery, container, false);
            container.addView(itemView);
            final ProgressBar pb = (ProgressBar) itemView.findViewById(R.id.process_pb);
            final SubsamplingScaleImageView iv = (SubsamplingScaleImageView) itemView.findViewById(R.id.image);
            iv.setMaxScale(5.0f);
            iv.setMinScale(0.5f);
            iv.setTag(position);

            SimpleTarget simpleTarget = new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition transition) {
                    BitmapDrawable bd = (BitmapDrawable) drawable;
                    Bitmap bm = bd.getBitmap();
                    pb.setVisibility(View.GONE);
                    iv.setImage(ImageSource.bitmap(bm));
                }
            };

            RequestListener listener = new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {

                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable drawable, Object model, Target target, DataSource dataSource, boolean isFirstResource) {

                    return false;
                }
            };

            Glide.with(PictureViewActivity.this)
                    .load(imgUrlList.get(position))
                    .listener(listener)
                    .into(simpleTarget);

            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        int position = (Integer) v.getTag();
                        mListener.onPictureClick(PicturePagerAdapter.this, v, position);
                    }
                }
            });
            return itemView;
        }

        @Override
        public int getCount() {
            return imgUrlList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        public void setOnClickListener(OnClickListener l) {
            mListener = l;
        }
    }

    private final class PisturePageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int arg0) {
            mContentPosTv.setText(String.valueOf(arg0 + 1));
            mContentTotalTv.setText(String.valueOf(imgUrlList.size()));
            if (null != imgDescriptionList && arg0 < imgDescriptionList.size()) {
                if (!"null".equals(imgDescriptionList.get(arg0))) {
                    mContentTv.setText(Html.fromHtml(imgDescriptionList.get(arg0)));
                } else {
                    mContentTv.setText("");
                }
            } else {
                mContentTv.setText("");
            }
        }
    }

    private android.animation.Animator mAnimatorTitle;
    private android.animation.Animator mAnimatorDescription;

    /**
     * @desc true:隐藏   false：显示
     * @author taoli
     * @time 2017/9/11 0011
     */
    private void displayTitleWithAnimator(final boolean bHiden) {
        if (mAnimatorTitle != null && mAnimatorTitle.isRunning()) {
            mAnimatorTitle.cancel();
        }
        if (bHiden) {
            mAnimatorTitle = ObjectAnimator.ofFloat(mTitleRl, "translationY", mTitleRl.getTranslationY(), -mTitleRl.getHeight());
            mAnimatorTitle.setInterpolator(new AccelerateInterpolator());
        } else {
            mAnimatorTitle = ObjectAnimator.ofFloat(mTitleRl, "translationY", mTitleRl.getTranslationY(), 0);
            mAnimatorTitle.setInterpolator(new DecelerateInterpolator());
        }
        mAnimatorTitle.setDuration(400);
        mAnimatorTitle.start();
    }

    /**
     * @desc true:隐藏   false：显示
     * @author taoli
     * @time 2017/9/11 0011
     */
    private void displayDescriptionWithAnimator(final boolean bHiden) {
        if (mAnimatorDescription != null && mAnimatorDescription.isRunning()) {
            mAnimatorDescription.cancel();
        }
        if (bHiden) {
            mAnimatorDescription = ObjectAnimator.ofFloat(mBottomRl, "translationY", mBottomRl.getTranslationY(), ScreenUtil.getScreenSize(getActivity())[1]);
            mAnimatorDescription.setInterpolator(new AccelerateInterpolator());
        } else {
            mAnimatorDescription = ObjectAnimator.ofFloat(mBottomRl, "translationY", mBottomRl.getTranslationY(), 0);
            mAnimatorDescription.setInterpolator(new DecelerateInterpolator());
        }
        mAnimatorDescription.setDuration(400);
        mAnimatorDescription.start();
    }

    private void sendBroadCaseRemountSDcard() {
        Intent intent = new Intent();
        // 重新挂载的动作
        intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        // 要重新挂载的路径
        intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
        sendBroadcast(intent);
    }

    public interface OnClickListener {
        public void onPictureClick(PagerAdapter adapter, View view, int position);
    }
}

